package persist

import (
	"github.com/pkg/errors"
	"golang.org/x/net/context"
	"gopkg.in/olivere/elastic.v5"
	"goruntimeCrawler/engine"
	"log"
	"math/rand"
	"strconv"
	"time"
)

func ItemSaver()  (chan engine.Item){
   out:=make(chan engine.Item)
   go func() {
   	    item:=<-out
		saveItem:=new(SaveItem)
		saveItem.Item=item

		_,err:=saveItem.save()
		if err !=nil{
			log.Printf("save Error:%s",err)
		}

   }()
   return out
}

type SaveItem struct {
	Item engine.Item
}

//调用服务保存数据
func (s *SaveItem) save() (string,error) {

	//http.Post( )
	client,err:=elastic.NewClient(
		   elastic.SetURL("http://118.24.148.120:9200"),
		   elastic.SetSniff(false),
		)
	if err !=nil{
		return "",err
	}
	if s.Item.Type==""{
		return "",errors.New("must supply type")
	}

	resp,err:=client.Index().
		Index("dating_profile").
		Type(s.Item.Type).
		BodyJson(s.Item).
		Id(s.Item.Id).
		Do(context.Background())
	if err!=nil{
		return "",err
	}
	return resp.Id,nil
}

//生成随机数
func (s *SaveItem) GetStringId() string  {
	timeInt:=time.Now().Unix()
	return strconv.FormatInt(timeInt,10)+strconv.Itoa(rand.Int())
}

//elasticSearch   全文搜索
